package com.woniuxy.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.core.service.AllUserService;
import com.woniuxy.core.service.CouponService;
import com.woniuxy.core.mapper.CouponMapper;
import com.woniuxy.core.service.UserCouponService;
import com.woniuxy.entity.AllUser;
import com.woniuxy.entity.Coupon;
import com.woniuxy.entity.UserCoupon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    private final AllUserService allUserService;
    private final UserCouponService userCouponService;

    @Autowired
    public CouponServiceImpl(
            AllUserService allUserService,
            @Lazy UserCouponService userCouponService) {
        this.allUserService = allUserService;
        this.userCouponService = userCouponService;
    }

    @Override
    @Transactional
    public boolean exchangeCoupon(Integer userId, Integer couponId) {
        Coupon coupon = this.getById(couponId);
        if (coupon == null) {
            return false;
        }

        AllUser user = allUserService.getById(userId);
        if (user == null || user.getCoin() < coupon.getNeedCoin()) {
            return false;
        }

        user.setCoin(user.getCoin() - coupon.getNeedCoin());
        allUserService.updateById(user);

        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(couponId);
        userCoupon.setStatus((byte) 1); // 未使用
        userCoupon.setCreateTime(new Date());

        return userCouponService.save(userCoupon);
    }
}
